package com.woniu.product.service.impl;

import java.math.BigDecimal;
import java.util.Date;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.common.dto.*;
import com.woniu.common.utils.*;
import com.woniu.product.dto.ProductAddDTO;
import com.woniu.product.dto.modifyProductDto;
import com.woniu.product.mapper.ZyImglistMapper;
import com.woniu.product.pojo.ZyImglist;
import com.woniu.product.pojo.ZyProduct;
import com.woniu.product.service.ZyImglistService;
import com.woniu.product.service.ZyProductService;
import com.woniu.product.mapper.ZyProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author ltyipx
 * @description 针对表【zy_product】的数据库操作Service实现
 * @createDate 2024-08-06 14:17:02
 */
@Service
public class ZyProductServiceImpl extends ServiceImpl<ZyProductMapper, ZyProduct>
        implements ZyProductService {
    @Autowired
    private ZyProductMapper productMapper;
    @Value("${snowflake.workerId}")
    private Long workerId;
    @Value("${snowflake.datacenterId}")
    private Long datacenterId;
    @Autowired
    private ZyImglistService imglistService;


    @Override
    public ResponseData<?> queryProduct(PageParam<ProductDto> params) {
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<ReturnProductDto> list = productMapper.queryProduct(params.getParam());
        PageInfo pageInfo = new PageInfo(list);
        return new ResponseData<>().success(pageInfo);
    }

    @Override
    public ResponseData<?> xiaJia(List<String> productId) {

        boolean update = lambdaUpdate().in(ZyProduct::getId, productId).set(ZyProduct::getStatus, 1).update();
        return update ? new ResponseData<>().success() : new ResponseData<>().fail();
    }

    @Override
    public ResponseData<?> shangJia(List<String> productId) {
        boolean update = lambdaUpdate().in(ZyProduct::getId, productId).set(ZyProduct::getStatus, 2).update();
        return update ? new ResponseData<>().success() : new ResponseData<>().fail();
    }

    @Override
    public ResponseData<?> updateProductType(XGFLDto xgfl) {
        boolean update = lambdaUpdate().in(ZyProduct::getId, xgfl.getProductId())
                .set(ZyProduct::getProductType, xgfl.getTypeId())
                .update();
        return update ? new ResponseData<>().success() : new ResponseData<>().fail();
    }

    @Override
    public ResponseData<?> addProduct(ZyProductDto form) throws Exception {
        long l = IdUtil.getSnowflake(workerId, datacenterId).nextId();
        form.setId(String.valueOf(l));
        form.setUpdateBy(GetCurrentUserId.getUserId());
        boolean flag = productMapper.addProduct(form);
        List<ZyImglist> zyImglists = new ArrayList<>();
        for (int i = 0; i < form.getImgList().size(); i++) {
            ZyImglist zyImglist = new ZyImglist();
            zyImglist.setId(String.valueOf(IdUtil.getSnowflake(workerId, datacenterId).nextId()));
            zyImglist.setProductId(form.getId());
            zyImglist.setImgSrc(form.getImgList().get(i));
            zyImglists.add(zyImglist);
        }
        boolean saveBatch = imglistService.saveBatch(zyImglists, form.getImgList().size());
        if (flag && saveBatch) {
            return new ResponseData<>().success();
        } else {
            return new ResponseData<>().fail();
        }
    }

    @Override
    public void updateStock(List<ForOrderProductDTO> productList) {
        for (ForOrderProductDTO product : productList) {
            ZyProduct queryProduct = getById(product.getId());
            queryProduct.setStock(queryProduct.getStock() - product.getBuyNum());
            productMapper.updateStock(queryProduct);
        }

    }

    @Override
    public void rollBackStock(List<OrderDetailDTO> list) {
        for (OrderDetailDTO orderDetailDTO : list) {
            lambdaUpdate()
                    .setSql("stock = stock+" + orderDetailDTO.getBuyNum())
                    .eq(ZyProduct::getId, orderDetailDTO.getProductId())
                    .update();
        }
    }

    @Override
    public List<ZyProduct> selectProduct(String productId) {
        return lambdaQuery().eq(ZyProduct::getId, productId)
                .list();
    }

    @Override
    @Transactional
    public Boolean productPush(List<ProductAddDTO> productAddDTOList) throws Exception {
        List<ZyProduct> productArrayList = new ArrayList<>();
        List<ZyImglist> imglistList = new ArrayList<>();
        for (ProductAddDTO productAddDTO : productAddDTOList) {
            ZyProduct zyProduct = new ZyProduct();
            zyProduct.setId(productAddDTO.getProductId());
            zyProduct.setName(productAddDTO.getProductName());
            zyProduct.setPrice(productAddDTO.getPrice());
            zyProduct.setProductType(productAddDTO.getProductTypeId());
            zyProduct.setProductImg(productAddDTO.getProductImg());
            zyProduct.setStatus(2);
            zyProduct.setStock(productAddDTO.getStock());
            zyProduct.setEcss(0);
            zyProduct.setCreateTime(new Date());
            zyProduct.setUpdateTime(new Date());
            zyProduct.setUpdateBy(GetManageUserNickName.getUserName());
            productArrayList.add(zyProduct);

            LambdaQueryWrapper<ZyImglist> imglistLambdaQueryWrapper = new LambdaQueryWrapper<>();
            imglistLambdaQueryWrapper.eq(ZyImglist::getProductId, productAddDTO.getProductId());
            imglistService.remove(imglistLambdaQueryWrapper);
            for (String s : productAddDTO.getImgList()) {
                ZyImglist zyImglist = new ZyImglist();
                zyImglist.setId(String.valueOf(new SnowflakeIdGenerator().nextId()));
                zyImglist.setProductId(productAddDTO.getProductId());
                zyImglist.setImgSrc(s);
                imglistService.save(zyImglist);
//                imglistService.saveOrUpdate(zyImglist, imglistLambdaQueryWrapper);
//                imglistList.add(zyImglist);
            }
        }
        saveOrUpdateBatch(productArrayList);

//        for (ZyImglist zyImglist : imglistList) {
//            LambdaQueryWrapper<ZyImglist> imglistLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            imglistLambdaQueryWrapper.eq(ZyImglist::getProductId, zyImglist.getProductId());
//            imglistService.saveOrUpdate(zyImglist, imglistLambdaQueryWrapper);
//        }
        return true;
    }

    @Override
    public ResponseData updateProductSales(ArrayList<ForOrderProductDTO> forOrderProductDTOS) {
        ArrayList<ZyProduct> zyProducts = new ArrayList<>();
        for (ForOrderProductDTO forOrderProductDTO : forOrderProductDTOS) {
            ZyProduct zyProduct = getById(forOrderProductDTO.getId());
            zyProduct.setCumulativeSales(zyProduct.getCumulativeSales() + forOrderProductDTO.getBuyNum());
            zyProducts.add(zyProduct);
        }
        updateBatchById(zyProducts);
        return new ResponseData().success();
    }

    @Override
    public ResponseData<?> modifyProduct(String id) {
        modifyProductDto modifyProductDto = productMapper.modifyProduct(id);
        List<ZyImglist> list = imglistService.lambdaQuery().eq(ZyImglist::getProductId, id).list();
        modifyProductDto.setImgList(list);
        return new ResponseData<>().success(modifyProductDto);
    }

    @Override
    public ResponseData<?> deleteProduct(List<String> productId) {

        boolean b = removeByIds(productId);
        return b ? new ResponseData<>().success() : new ResponseData<>().fail();
    }
}




